import asyncpg
from aiohttp import web
from aiohttp.web_request import Request

routes = web.RouteTableDef()

DB_KEY = "database"


async def create_database_pool(app):
    print("创建数据库池...")
    pool = await asyncpg.create_pool(
        host="127.0.0.1",
        port=5432,
        user="around",
        password="zhouwei",
        database="products",
        min_size=6,
        max_size=6,
    )
    app[DB_KEY] = pool


async def destroy_database_pool(app):
    print("销毁数据库连接池...")
    pool = app[DB_KEY]
    await pool.close()


@routes.get('/brand')
async def brand(request: Request):
    connection = request.app[DB_KEY]
    brand_query = "select brand_id, brand_name from brand"
    results = await connection.fetch(brand_query)
    result_as_dict = [dict(brand) for brand in results]
    return web.json_response(result_as_dict)


app = web.Application()
app.on_startup.append(create_database_pool)
app.on_cleanup.append(destroy_database_pool)
app.router.add_routes(routes)
web.run_app(app)
